﻿// (c)2010 David Schwarz (david.schwarz@live.com)
// This file is licensed under GNU GPL v2 license, see more at http://www.gnu.org/licenses/gpl-2.0.html
namespace Z2
{

	#region Using

	using System;
	using System.IO;
	using System.Diagnostics;

	#endregion

	static class Program
	{

		#region Members

		private static Zelvici2 _game;
		private static object _syncRoot = new object();
		private const string ErrorFile = "Zelvici2_Error.txt";

		#endregion

		#region Properties

		internal static Zelvici2 CurrentGame
		{
			get { return _game; }
		}

		#endregion

		#region Entry Point

		static void Main(string[] args)
		{
#if DEBUG
			Debug.Listeners.Add(new LogListener());
#endif
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Program.UnhandledException);
			string runMap = string.Empty;
			if (args != null && args.Length > 0)
			{
				runMap = args[0];
			}

			using (_game = new Zelvici2(runMap))
			{
				_game.Run();
			}
		}

		#endregion

		#region Event Handlers

		private static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			lock (_syncRoot)
			{
				try
				{
					_game.Pause();
					ExceptionReport.Show((Exception) e.ExceptionObject);
					string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Program.ErrorFile);
					using (TextWriter writer = (TextWriter) File.CreateText(path))
					{
						writer.Write(e.ExceptionObject);
					}
				}
				finally
				{
					_game.Exit();
					_game.Dispose();
					Process.GetCurrentProcess().Kill();
				}
			}
		}
		
		#endregion

	}
}

